<template>
  <div class="upload-img">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img v-if="value" v-showAvatar :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <!-- 删除按钮 -->
    <i v-if="value" class="el-icon-close del" @click="del" />
    <!-- 上传进度条 -->
    <!-- 进度值从0-100 -->
    <!--
        vue动画条件：进入/离开
        实现
          1:transition包住
          2：加入name="xxx"
            .xxx-enter:进入前状态
            .xxx-enter-active:进入过程中一直存在的
            .xxx-leave-to:离开时状态
            .xxx-leave-active
     -->
    <transition name="xxx">
      <el-progress v-if="showProgress" :percentage="percentage" />
    </transition>
    <!-- 头像预览
    1：布局
       鼠标移入显示预览按钮
       弹框显示
    2:点击预览
        显示弹框，弹框内显示大图片
     -->
    <!-- 预览图标 -->
    <i v-if="value" class="el-icon-zoom-in show-big" @click="showPic = true" />
    <el-dialog title="图片预览" :visible.sync="showPic" width="600px">
      <img v-showAvatar :src="value" style="width: 100%" alt="">
    </el-dialog>
  </div>
</template>
<script>
import Cos from 'cos-js-sdk-v5'
/*
1:安装 cos-js-sdk-v5
2：导入
3：实例化（需要使用密钥）
4:调用上传方法
*/
const cos = new Cos({
  SecretId: 'AKIDNXR8bpeSF1JL8EyZopxRfdHgqGUeuEn8',
  SecretKey: 'HJ9mAbQEn7jgjY9swEI6yAamk7MN8hty'
})
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      //   imageUrl: ''
      percentage: 0,
      showProgress: false,
      showPic: false
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG,PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    httpRequest(res) {
      console.log(res)
      this.showProgress = true
      cos.putObject(
        {
          Bucket: 'dhf81-1305249343' /* 必须存储桶 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: Date.now() + '' /* 必须 */,
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            this.percentage = +(progressData.percent * 100).toFixed(1)
            if (progressData.percent === 1) {
              setTimeout(() => {
                this.showProgress = false
                this.percentage = 0
              }, 1000)
            }
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          if (!err) {
            // this.value = 'http://' + data.Location
            this.$emit('input', 'http://' + data.Location)
          }
          console.log(err || data)
        }
      )
    },
    // 删除
    del() {
      this.$emit('input', '')
    }
  }
}
</script>
<style lang="scss" scoped>
// scoped:只管当前组件和子组件最外层
// /deep/  >>>   ::v-deep    vue3:  :deep(class)
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-img {
  position: relative;
  width: 178px;
  height: 178px;
  &:hover {
    .del {
      display: block;
    }
    .show-big {
      display: block;
    }
  }
  .del {
    position: absolute;
    top: 10px;
    right: 10px;
    color: red;
    font-size: 30px;
    cursor: pointer;
    display: none;
  }
  .show-big {
    position: absolute;
    top: 10px;
    right: 60px;
    color: red;
    font-size: 30px;
    cursor: pointer;
    display: none;
  }
}
.xxx-enter {
  opacity: 0;
  transform: translateY(-20px);
}
.xxx-enter-active {
  transition: all 0.5s;
}
.xxx-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
.xxx-leave-active {
  transition: all 0.5s;
}
</style>
